# -*- coding: utf8-*-
from Member import Member
import Utils
from WorkRecord import WorkRecord
import sys
import Config
from datetime import datetime
from Utils import formatList
from Utils import ExcelStyle
import logging.handlers
import time
import logging
import xlwt
import os


logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s',level=1)


def is_valid_date(str):
    '''判断是否是一个有效的日期字符串'''
    try:
        time.strptime(str, "%Y/%m/%d")
        return True
    except:
        try:
            time.strptime(str,"%Y-%m-%d")
            return True
        except:
            return False

def formateDate(d):
    if isinstance(d,basestring):
        d = d.replace("-","/")
    return datetime.strptime(d, "%Y/%m/%d").date()


def parseParam(args):
    '''check the input args are valid'''

    logging.info("parseParam begin")
    if (len(args)) < 3:
        logging.error("please input start date and end date, format like 2016/08/01 or 2016-08-01")
        exit()
    startDate = args[1]
    endDate = args[2]
    if not is_valid_date(startDate) or not is_valid_date(endDate):
        logging.error("invalid start date %s or end date %s"%(startDate,endDate))
        exit()

    startDate = formateDate(startDate)
    endDate = formateDate(endDate)
    if startDate > endDate:
        logging.error("startDate should be less than the endDate")
        exit()
    logging.info("parseParam end, params are valid")
    return (startDate,endDate)

if __name__ == '__main__':
    allFiles = os.listdir(".")
    for file in allFiles:

        if file.endswith(".xls"):
            os.remove(file)
    #if (len(sys.argv)) > 3:
    #    (startDate,endDate) = parseParam(sys.argv)
    (startDate, endDate, allRecords) = Utils.readXls_new()
    startDate = formateDate(startDate)
    endDate = formateDate(endDate)
    allWorkDays = []
    allWorkDays = Utils.getAllWorkDay(startDate,endDate)
    if(len(sys.argv)) == 7:
        Member.WORKING_TIME = sys.argv[3]
        Config.OFF_TIME = sys.argv[4]
        Config.OVERWORK_TIME = sys.argv[5]
        Config.OVERWORK_TIME_FRIDAY = sys.argv[6]
    #allRecords = Utils.readXls()

    #allRecords = xlsDemo.getFinalOutput()
    allMembers = []

    for name,record in allRecords.items():
       workRecords = list()
       for r in record:
           workRecord = WorkRecord(r[0], r[1], r[2])
           workRecords.append(workRecord)
       member = Member(name,workRecords)

       allMembers.append(member)


    customeName = str(startDate).replace("/", "") + "_" + str(endDate).replace("/", "")

    #filename = "d:\\AttendanceRecord\\" + customeName + ".xls"
    filename = customeName + ".xls"
    book = Utils.creatNewBook()
    index_workOvertime = 1
    index_oof = 0
    index_late=0
    index_leaveEarly = 0
    index_dailyworkover = 0
    index_swipe = 0
    index_askforleave = 0

    alignment = xlwt.Alignment()  # Create Alignment
    alignment.horz = xlwt.Alignment.HORZ_LEFT  # May be: HORZ_GENERAL, HORZ_LEFT, HORZ_CENTER, HORZ_RIGHT, HORZ_FILLED, HORZ_JUSTIFIED, HORZ_CENTER_ACROSS_SEL, HORZ_DISTRIBUTED
    alignment.vert = xlwt.Alignment.VERT_CENTER  # May be: VERT_TOP, VERT_CENTER, VERT_BOTTOM, VERT_JUSTIFIED, VERT_DISTRIBUTED
    style = xlwt.XFStyle()  # Create Style
    style.alignment = alignment
    pattern = xlwt.Pattern()  # Create the Pattern

    lateStyle = ExcelStyle()
    oofStyle = ExcelStyle()
    overworkStyle = ExcelStyle()
    leaveEarylyStyle = ExcelStyle()
    dailyOverWorkStyle = ExcelStyle()

    exceptionStyle = ExcelStyle()
    askforleaveStyle = ExcelStyle()



    for memberA in allMembers:



        mylateDays = memberA.getLateForWorkDays()

        try:
            sheet_late = Utils.addSheet(book, "迟到")

            Utils.writeToExcel(sheet_late, 0, 0, "姓名")
            Utils.writeToExcel(sheet_late,0,1,"迟到次数")
            Utils.writeToExcel(sheet_late, 0, 2, "迟到日期")
            Utils.writeToExcel(sheet_late, 0, 3, "迟到时长")
            Utils.writeToExcel(sheet_late, 0, 4, "晚走时间是否超过迟到时间")
            #Utils.writeToExcel(sheet, 1, 0, memberA.name)
        except:
            pass



        if(len(mylateDays)>0):
            lateStyle.setPattern()
            sheet_late.write_merge(1+index_late,len(mylateDays)+index_late,0,0,memberA.name,lateStyle.style)
            sheet_late.write_merge(1+index_late,len(mylateDays)+index_late,1,1, len(mylateDays), lateStyle.style)
            i = 0
            for key,value in mylateDays.items():
                Utils.writeToExcel(sheet_late, 1+i+index_late, 2, key,lateStyle.style)
                lateduration = str(value[0])
                print "lateduration:"+lateduration
                if key in memberA.getWorkOvertime(allWorkDays):

                    print str(value[0])
                    Utils.writeToExcel(sheet_late, 1+i+index_late, 3, str(value[0])+"分钟（加班日）",lateStyle.style)


                else:
                    Utils.writeToExcel(sheet_late, 1 + i+index_late, 3, str(value[0]) + "分钟",lateStyle.style)


                Utils.writeToExcel(sheet_late, 1 + i+index_late, 4, str(value[1]),lateStyle.style)
                i += 1
            index_late +=len(mylateDays)
        sheet_late.col(1).width = 256 * 10
        sheet_late.col(2).width = 256 * 10
        sheet_late.col(3).width = 256 * 10
        sheet_late.col(4).width = 256 * 25

        myOOFDays = memberA.getOOFDay(allWorkDays)

        try:
            sheet_oof = Utils.addSheet(book, "缺勤")

            Utils.writeToExcel(sheet_oof, 0, 0, "姓名")
            Utils.writeToExcel(sheet_oof, 0, 1, "缺勤天数")
            Utils.writeToExcel(sheet_oof, 0, 2, "缺勤日期")
            sheet_oof.col(2).width = 256 * 10
        except:
            pass




        if (len(myOOFDays) > 0):
            oofStyle.setPattern()
            Utils.writeToExcel(sheet_oof, 1 + index_oof, 0, memberA.name,oofStyle.style)
            Utils.writeToExcel(sheet_oof, 1 + index_oof, 1, len(myOOFDays),oofStyle.style)
            Utils.writeToExcel(sheet_oof, 1 + index_oof, 2, myOOFDays,oofStyle.style)
            index_oof += 1

        myWorkOvertimeDays = memberA.getWorkOvertime(allWorkDays)
        try:
            sheet_workovertime = Utils.addSheet(book, "加班")
            sheet_workovertime.col(3).width = 256 * 26
            Utils.writeToExcel(sheet_workovertime, 0, 0, "姓名")
            Utils.writeToExcel(sheet_workovertime, 0, 1, "加班天数")
            Utils.writeToExcel(sheet_workovertime, 0, 2, "加班日期")
            Utils.writeToExcel(sheet_workovertime, 0, 3, "加班时长")
        except:
            pass


        if (len(myWorkOvertimeDays) > 0):
            # 合并单元格

            overworkStyle.setPattern()
            sheet_workovertime.write_merge(index_workOvertime, len(myWorkOvertimeDays) + index_workOvertime - 1, 0, 0,
                                           memberA.name,overworkStyle.style)
            sheet_workovertime.write_merge(index_workOvertime, len(myWorkOvertimeDays) + index_workOvertime - 1, 1, 1,
                                           len(myWorkOvertimeDays),overworkStyle.style)
            i = 0
            for key, value in myWorkOvertimeDays.items():
                Utils.writeToExcel(sheet_workovertime, index_workOvertime + i, 2, key,overworkStyle.style)
                Utils.writeToExcel(sheet_workovertime, index_workOvertime + i, 3, value,overworkStyle.style)
                i += 1

            sheet_workovertime.col(2).width = 256 * 10
            index_workOvertime += len(myWorkOvertimeDays)



        myearlyDays = memberA.getLeaveEarly()
        try:
            sheet_leaveEarly = Utils.addSheet(book, "早退")

            Utils.writeToExcel(sheet_leaveEarly, 0, 0, "姓名")
            Utils.writeToExcel(sheet_leaveEarly, 0, 1, "早退次数")
            Utils.writeToExcel(sheet_leaveEarly, 0, 2, "早退日期")
            Utils.writeToExcel(sheet_leaveEarly, 0, 3, "早退时长")
        except:
            pass
        if (len(myearlyDays) > 0):
            leaveEarylyStyle.setPattern()
            # Utils.writeToExcel(sheet, 1, 0, memberA.name)
            sheet_leaveEarly.write_merge(1 + index_leaveEarly, len(myearlyDays) + index_leaveEarly, 0, 0, memberA.name,leaveEarylyStyle.style)
            sheet_leaveEarly.write_merge(1 + index_leaveEarly, len(myearlyDays) + index_leaveEarly, 1, 1, len(myearlyDays),
                                         leaveEarylyStyle.style)
            i = 0
            for key, value in myearlyDays.items():
                Utils.writeToExcel(sheet_leaveEarly, 1 + i + index_leaveEarly, 2, key,leaveEarylyStyle.style)
                if key in memberA.getWorkOvertime(allWorkDays):
                    Utils.writeToExcel(sheet_leaveEarly, 1 + i + index_leaveEarly, 3, str(value) + "分钟（加班日）",leaveEarylyStyle.style)
                else:
                    Utils.writeToExcel(sheet_leaveEarly, 1 + i + index_leaveEarly, 3, str(value) + "分钟",leaveEarylyStyle.style)
                i += 1
            index_leaveEarly += len(myearlyDays)
            sheet_leaveEarly.col(1).width = 256 * 10
            sheet_leaveEarly.col(2).width = 256 * 20

        mydailyOverWorkdDays = memberA.getDailyOverWork()

        try:
            sheet_dailyovertime = Utils.addSheet(book, "工作日加班")

            Utils.writeToExcel(sheet_dailyovertime, 0, 0, "姓名")
            Utils.writeToExcel(sheet_dailyovertime, 0, 1, "加班天数")
            Utils.writeToExcel(sheet_dailyovertime, 0, 2, "加班日期")
        except:
            pass
        if (len(mydailyOverWorkdDays) > 0):
            dailyOverWorkStyle.setPattern()
            #print "dailyOverWorkStyle:"+str(dailyOverWorkStyle.pattern)
            logging.info("dailyOverWorkStyle: %s " % dailyOverWorkStyle.pattern)
            sheet_dailyovertime.col(2).width = 256 * 10
            Utils.writeToExcel(sheet_dailyovertime, 1 + index_dailyworkover, 0, memberA.name,dailyOverWorkStyle.style)
            Utils.writeToExcel(sheet_dailyovertime, 1 + index_dailyworkover, 1, len(mydailyOverWorkdDays),dailyOverWorkStyle.style)
            Utils.writeToExcel(sheet_dailyovertime, 1 + index_dailyworkover, 2, mydailyOverWorkdDays,dailyOverWorkStyle.style)
            index_dailyworkover += 1


        myExceptionDays = memberA.getSwiptingExcetpion()

        try:

            sheet_swipe = Utils.addSheet(book, "刷卡异常")

            Utils.writeToExcel(sheet_swipe, 0, 0, "姓名")
            Utils.writeToExcel(sheet_swipe, 0, 1, "异常次数")
            Utils.writeToExcel(sheet_swipe, 0, 2, "异常日期")
            Utils.writeToExcel(sheet_swipe, 0, 3, "首次刷卡")
            Utils.writeToExcel(sheet_swipe, 0, 4, "末次刷卡")
        except:
            pass
        if (len(myExceptionDays) > 0):
            exceptionStyle.setPattern()
            sheet_swipe.col(1).width = 256 * 10
            # Utils.writeToExcel(sheet, 1, 0, memberA.name)
            sheet_swipe.write_merge(1 + index_swipe, len(myExceptionDays) + index_swipe, 0, 0, memberA.name,exceptionStyle.style)
            sheet_swipe.write_merge(1 + index_swipe, len(myExceptionDays) + index_swipe, 1, 1, len(myExceptionDays),
                                    exceptionStyle.style)
            i = 0
            for day in myExceptionDays:
                Utils.writeToExcel(sheet_swipe, 1 + i + index_swipe, 2, day.workDate,exceptionStyle.style)

                Utils.writeToExcel(sheet_swipe, 1 + i + index_swipe, 3, day.startTime if day.hasStartTime() else "无",exceptionStyle.style)
                Utils.writeToExcel(sheet_swipe, 1 + i + index_swipe, 4, day.endTime if day.hasEndTime() else "无",exceptionStyle.style)
                i += 1
            index_swipe += len(myExceptionDays)
        sheet_swipe.col(2).width = 256 * 10
        myaskForLeaveDays = memberA.getAskforLeave()

        try:
            sheet_askforleave = Utils.addSheet(book, "请假")

            Utils.writeToExcel(sheet_askforleave, 0, 0, "姓名")
            Utils.writeToExcel(sheet_askforleave, 0, 1, "请假日期")
            Utils.writeToExcel(sheet_askforleave, 0, 2, "请假时长")

            sheet_askforleave.col(1).width = 256 * 10
        except:
            pass
            # Utils.writeToExcel(sheet, 1, 0, memberA.name)

        if (len(myaskForLeaveDays) > 0):
            askforleaveStyle.setPattern()
            sheet_askforleave.write_merge(1 + index_askforleave, len(myaskForLeaveDays) + index_askforleave, 0, 0,
                                          memberA.name,askforleaveStyle.style)
            i = 0
            for key, value in myaskForLeaveDays.items():
                Utils.writeToExcel(sheet_askforleave, 1 + i + index_askforleave, 1, key,askforleaveStyle.style)

                Utils.writeToExcel(sheet_askforleave, 1 + i + index_askforleave, 2, value,askforleaveStyle.style)

                i += 1
            index_askforleave += len(myaskForLeaveDays)

    book.save(filename)

